package org.kukker.activity;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.kukker.DBHelper;
import org.kukker.R;
import org.kukker.R.id;
import org.kukker.R.layout;
import org.kukker.app.KukkerApp;
import org.kukker.event.Event;
import org.kukker.list.IKukkerListItemListener;
import org.kukker.list.IKukkerListItemView;
import org.kukker.list.KukkerListAdapter;
import org.kukker.list.KukkerListView;
import org.kukker.upcoming.UpcomingEvent;
import org.kukker.upcoming.UpcomingWebService;
import org.kukker.view.EventDetailView;
import org.kukker.view.EventDetailView.IEventDetailViewListener;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.ListActivity;
import android.app.TimePickerDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.util.DateFormat;
import android.util.Log;
import android.view.Menu;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup;
import android.view.Menu.Item;
import android.view.Menu.OnClickListener;
import android.view.Menu.OnSelectionListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Transformation;
import android.view.animation.TranslateAnimation;
import android.view.animation.Animation.AnimationListener;
import android.widget.AbsoluteLayout;
import android.widget.Adapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.AdapterView.OnItemClickListener;
import android.xml.dom.DocumentImpl;
import android.xml.dom.ElementImpl;

public class CreateNewEventActivity extends Activity {
	/** Called when the activity is first created. */
	// where we display the selected date and time

	// date and time
	private int mYear;
	private int mMonth;
	private int mDay;
	private int mHour;
	private int mMinute;

	private OnClickListener mMenuItemSaveClickListener;
	private OnClickListener mMenuReturnClickListener;
	private OnClickListener mMenuNewClickListener;
	private DatePicker.OnDateSetListener mDateSetListener;
	private TimePicker.OnTimeSetListener mTimeSetListener;
	private View.OnClickListener mDateValueOnClickListener;
	private View.OnClickListener mTimeValueOnClickListener;

	DBHelper dbHelper;

	TextView name;
	TextView description;
	TextView venueName;
	TextView venueAddress;
	TextView venueCountry;
	TextView venueCity;
	Button dateValue;
	Button timeValue;

	Event mEvent;
	
	Calendar mCalendar;
	
	private void getWidgets() {
		name = (TextView) findViewById(R.id.eventnew_value_name);
		description = (TextView) findViewById(R.id.eventnew_value_description);
		venueName = (TextView) findViewById(R.id.eventnew_value_venuename);
		venueAddress = (TextView) findViewById(R.id.eventnew_value_address);
		venueCountry = (TextView) findViewById(R.id.eventnew_value_country);
		venueCity = (TextView) findViewById(R.id.eventnew_value_city);
		dateValue = (Button) findViewById(R.id.eventnew_value_datevalue);
		timeValue = (Button) findViewById(R.id.eventnew_value_timevalue);

	}

	@Override
	protected void onCreate(Bundle icicle) {

		super.onCreate(icicle);

		this.setTitle("Create new event");
		this.mEvent = new Event();
		this.mEvent.setIsSaved(false);
		
		dbHelper = new DBHelper(this);
		this.initListeners();

		setContentView(R.layout.create_new_event2);
		this.getWidgets();

		// Button pickDate = (Button)
		// findViewById(R.id.eventnew_value_datevalue);

		dateValue.setOnClickListener(this.mDateValueOnClickListener);
		dateValue.setText("click to set date");
		// Button pickTime = (Button)
		// findViewById(R.id.eventnew_value_timevalue);

		timeValue.setOnClickListener(this.mTimeValueOnClickListener);
		timeValue.setText("click to set time");

		mCalendar = Calendar.getInstance();
		mYear = mCalendar.get(Calendar.YEAR);
		mMonth = mCalendar.get(Calendar.MONTH) + 1;
		mDay = mCalendar.get(Calendar.DAY_OF_MONTH);
		mHour = mCalendar.get(Calendar.HOUR_OF_DAY);
		mMinute = mCalendar.get(Calendar.MINUTE);
		
		
		
		updateDisplay();
		updateTimeDisplay();
		
	}

	private void updateDisplay() {
		String monthName="";
		monthName = KukkerApp.getMonthName(mMonth);
		
		dateValue.setText(new StringBuilder().append(monthName).append(" ")
				.append(mDay).append(", ").append(mYear).append(" "));
		// .append(pad(mHour)).append(":")
		// .append(pad(mMinute)));
		
	
	}

	private void updateTimeDisplay() {
		timeValue.setText(new StringBuilder().append(pad(mHour)).append(":")
				.append(pad(mMinute)));
	}

	private static String pad(int c) {
		if (c >= 10)
			return String.valueOf(c);
		else
			return "0" + String.valueOf(c);
	}
	
	public boolean onOptionsItemSelected(Item item) {

		super.onOptionsItemSelected(item);
		switch (item.getId()) {
		
		
		
		}	
		
		return true;
	
	}
	
	public boolean onCreateOptionsMenu(Menu menu) {
		
		// has event been saved?
		boolean isSaved = this.mEvent.getIsSaved();
		Item menuSaveUpdate;
		if(!isSaved){
			menuSaveUpdate = menu.add(0, 0, "Save");				
			menuSaveUpdate.setShortcut('1', 's');
			
		}else{
			menuSaveUpdate = menu.add(0, 0, "Update");	
			menuSaveUpdate.setShortcut('1', 's');
		}
		
		menuSaveUpdate.setClickListener(this.mMenuItemSaveClickListener);
		
		Item menuReturn;
		menuReturn = menu.add(0,1,"Return");
		menuReturn.setClickListener(this.mMenuReturnClickListener);
		
		
		Item menuNew;		
		menuNew = menu.add(0,2,"New");		
		menuNew.setClickListener(this.mMenuNewClickListener);
		
		
		return true;

	}

	public void onDestroy() {
		super.onDestroy();
		
		this.dbHelper.close();
	}

	private void resetFields(){
		name.setText("");
		description.setText("");
		venueName.setText("");
		venueAddress.setText("");
		venueCountry.setText("");
		venueCity.setText("");
		dateValue.setText("click to set date");
		timeValue.setText("click to set time");
	}
	
	private void saveEvent() {

		
		this.mEvent.name = this.name.getText().toString();
		this.mEvent.description = this.description.getText().toString();
		this.mEvent.venueAddress = this.venueAddress.getText().toString();
		this.mEvent.venueName = this.venueName.getText().toString();
		this.mEvent.venueCity = this.venueCity.getText().toString();
		this.mEvent.venueCountry = this.venueCountry.getText().toString();
		
		String startDate = KukkerApp.constructDateString(mYear, mMonth, mDay);		
		Log.i("debug","startDate: "+startDate);
		
		this.mEvent.startDate = startDate;
		
		this.mEvent.startTime = this.timeValue.getText().toString();
		this.mEvent.typeId = 1; //1 for Event TODO rearchitect this
		this.mEvent.originId = 0; //0 for local
		
		if(!this.mEvent.getIsSaved()){
			dbHelper.insertEvent(this.mEvent);
		}
		else{
			dbHelper.updateEvent(this.mEvent);
		}

	}

	private void initListeners() {
		this.mTimeValueOnClickListener = new View.OnClickListener() {
			public void onClick(View v) {
				new TimePickerDialog(CreateNewEventActivity.this,
						mTimeSetListener, "Set the time", mHour, mMinute, false)
						.show();
			}
		};

		this.mDateValueOnClickListener = new View.OnClickListener() {
			public void onClick(View v) {
				new DatePickerDialog(CreateNewEventActivity.this,
						mDateSetListener, mYear, mMonth - 1, mDay, Calendar.SUNDAY)
						.show();
			}
		};

		this.mMenuItemSaveClickListener = new OnClickListener() {

			@Override
			public boolean onClick(Item arg0) {
				Log.i("debug", "save selected");
				saveEvent();
				setResult(2);
				finish();				
				return true;
			}

		};

		this.mMenuNewClickListener = new OnClickListener() {

			@Override
			public boolean onClick(Item arg0) {
				mEvent.setIsSaved(false);
				
				resetFields();				
				return true;
			}

		};

		this.mMenuReturnClickListener = new OnClickListener() {
			@Override
			public boolean onClick(Item arg0) {
				setResult(Activity.RESULT_OK);
				finish();
				return true;
			}

		};

		
		this.mDateSetListener = new DatePicker.OnDateSetListener() {

			public void dateSet(DatePicker view, int year, int monthOfYear,
					int dayOfMonth) {
				mYear = year;
				mMonth = monthOfYear + 1;
				mDay = dayOfMonth; 
				//NOTE: android datepicker use zer0-starting index for the months
				//but the app uses one-starting index for months.
				
				Log.i("debug","ondateset: "+mMonth+","+mYear+","+mDay);
				
				updateDisplay();
			}
		};

		this.mTimeSetListener = new TimePicker.OnTimeSetListener() {

			public void timeSet(TimePicker view, int hourOfDay, int minute) {
				mHour = hourOfDay;
				mMinute = minute;
				
				mCalendar.set(mYear, mMonth, mDay, mHour, mMinute);
				
				updateTimeDisplay();
			}
		};

	}

}
